<?php

/**
 * 聚合数据接口类
 */
class Juhe {

    //聚合数据 KEY【IP地址】
	private static $IPKEY = '60f977ec704399b808e9e827e8fd45a2';

    //聚合数据 KEY【短信API服务】
    private static $SMSKEY = '1f4c9b6ab2fa27d75a1f1cee8bb525f2';

    /**
     * @title 根据查询的IPv4地址，查询该IPv4所属的区域，城市级查询。
     * @param $ip
     * @return false|string|null
     * {
        "resultcode": "200",
        "reason": "查询成功",
        "result": {
        "Country": "中国",
        "Province": "江苏",
        "City": "苏州",
        "Isp": "联通"
        },
        "error_code": 0
        }
     */
    static function getIpAddress($ip){
        $url = "http://apis.juhe.cn/ip/ipNewV3?ip=%s&key=%s";
        $url= sprintf($url, $ip, self::$IPKEY);
        $response = iconv('GBK','UTF-8//IGNORE',file_get_contents($url));
        $result = json_decode($response,true);
        if( $result['resultcode'] != 200 || ( isset($result['error_code']) && $result['error_code'] != 0 ) ){
            $message = $result['reason'];
            return null;
        }
        return json_encode($result['result'],JSON_UNESCAPED_UNICODE);
    }

    /**
     * @title 聚合数据短信接口
     * @param $mobile
     * @param $content
     * @return mixed
     * 失败实示例
     * {
        "reason": "错误的短信模板ID,请通过后台确认!!!",
        "result": [],
        "error_code": 205402
        }
     * 成功示例
     * {
        "reason": "短信发送成功",
        "result": {
            "count": 1, //发送数量
            "fee": 1, //扣除条数
            "sid": "23d6bc4913614919a823271d820662af" // 短信ID
        },
        "error_code": 0 //发送成功
        }
     */
    static function sendSms( $code, $mobile, $vars ){
        $result = ['status' => 1, "message" => '', 'extend_info' => ''];
        $tplCode = array();
        $tplCode['smsCode']['tplid'] = 252303;
        $tplCode['smsCode']['vars'] = ['code'];
        $tplCode['smsCode']['tplContent']= "【盾妈妈】您的验证码是#code#。如非本人操作，请忽略本短信";
        if( !isset($tplCode[$code]) ){
            $result['status'] = 0;
            $result['message'] = "不合法的短信模板编码";
            return $result;
        }
        $smsContent = $tplCode[$code]['tplContent'];
        foreach( $vars as $key => $val ){
            if( !in_array($key,$tplCode['smsCode']['vars']) ){
                $result['status'] = 0;
                $result['message'] = "存在不合法的参数 key = ".$key;
                return $result;
            }else{
                $smsContent = str_ireplace("#{$key}#", $val, $smsContent);
            }
        }
        //短信请求体
        $data = array(
            'tpl_id'    => $tplCode[$code]['tplid'],            //短信模板ID，请参考个人中心短信模板设置
            'mobile'    => $mobile,                             //接收短信的手机号码
            'vars'      => json_encode($vars),                  //短信内容，最多350个汉字
            'key'       => self::$SMSKEY,                       //在个人中心->我的数据,接口名称上方查看
            'dtype'     => 'json',                              //返回数据的格式,xml或json，默认json
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://v.juhe.cn/sms/send");
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec( $ch );
        curl_close( $ch );
        $returndata = json_decode($res,true);
        $relateCode = 'sms_juhe';
        $extendInfo = "";
        $relateSn = "";
        $remark = "";
        $status = 0;
        if( $returndata['error_code'] != 0 ){
            $result['status'] = 0;
            $result['message'] = $returndata['reason'];
            $remark = $returndata['reason'];
            $extendInfo = json_encode($returndata,JSON_UNESCAPED_UNICODE);
            $status = 2;
        }else{
            $result['status'] = 1;
            $result['message'] = $returndata['reason'];
            $remark = $returndata['reason'];
            $extendInfo = json_encode($returndata,JSON_UNESCAPED_UNICODE);
            $relateSn = $returndata['result']['sid'];
            $status = 1;
        }
        SmsRecord::add( $mobile, $smsContent, $relateCode, $relateSn, $remark, $extendInfo,$status);
        return $result;
    }
}

//短信记录
class SmsRecord
{
    /**
     * @param int $mobile
     * @param string $content
     * @param string $relate_code
     * @param string $relate_sn
     * @param string $remark
     * @param string $extend_info
     * @param int $status
     */
    public static function add($mobile = 0, $content = '', $relate_code = '', $relate_sn = '', $remark = '', $extend_info = '', $status = 1)
    {
        $data = array();
        $data['type'] = 2;
        $data['channel'] = 2;
        $data['mobile'] = trim($mobile);
        $data['content'] = $content;
        $data['relate_code'] = $relate_code;
        $data['relate_sn'] = $relate_sn;
        $data['status'] = $status;
        $data['remark'] = $remark;
        $data['remark'] = $remark;
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['extend_info'] = $extend_info;
        M('message_records')->add($data);
    }
}

?>
